import { http } from "@/utils/http";
import type { ApiResponse } from "../user";
import { ensureArray, toNumber } from "@/api/_helpers";

const ORG_ENDPOINT = "/system/org/tree";

export interface OrgTreeNode {
  id: number;
  parent_id?: number | null;
  name: string;
  type?: string;
  children?: Array<OrgTreeNode>;
  [key: string]: any;
}

const mapNode = (node: Record<string, any>): OrgTreeNode => ({
  id: toNumber(node.id, 0),
  parent_id: node.parent_id ?? null,
  name: node.name ?? node.title ?? "",
  type: node.type ?? node.category ?? "",
  children: Array.isArray(node.children)
    ? node.children.map(mapNode)
    : undefined
});

const fetchTree = async (
  params?: Record<string, any>
): Promise<Array<OrgTreeNode>> => {
  const res = await http.request<ApiResponse<any>>("get", ORG_ENDPOINT, {
    params
  });
  const payload = (res?.data as Record<string, any>) ?? {};
  const list = ensureArray<Record<string, any>>(
    payload.list ?? payload.data ?? payload
  );
  return list.map(mapNode);
};

export default {
  fetchTree
};
